package com.cvte.shop.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author DaiShubo
 * @version 1.0
 * @description 统一日志方法管理
 * @createTime 2020/7/29 4:58 下午
 * @since 1.7
 **/
@Aspect
@Component
@Slf4j
public class WebLogAspect {

    ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    @Pointcut("@annotation(com.cvte.shop.annotation.EableLog)")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info("REQUEST URL : {}" , request.getRequestURL().toString());
        log.info("REQUEST HTTP_METHOD : {}" , request.getMethod());
        log.info("REQUEST IP : {}" , request.getRemoteAddr());
        log.info("REQUEST CLASS_METHOD : {}" , joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("REQUEST ARGS : {}" , Arrays.toString(joinPoint.getArgs()));

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("RESPONSE DATA : {}" , JSON.toJSONString(ret));
        log.info("METHOD SPEND TIME : {}ms", (System.currentTimeMillis() - startTime.get()));
    }

}
